package com.luoling.download;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.luoling.util.DateUtils;
import com.luoling.util.JsonUtils;
import lombok.Data;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.poi.util.StringUtil;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Description:
 * Copyright:   Copyright (c)2024
 * Company:
 *
 * @author: 张李鑫
 * @version: 1.0
 * Create at:   2024-07-18 18:05:54
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2024-07-18     张李鑫                     1.0         1.0 Version
 */
public class Upload {
    //http://prod.db-upgrade-tools.ctjsoft.com/api/v1/upgradePackage?uploadType=1
    //http://prod.db-upgrade-tools.ctjsoft.com/api/v1/upgradePackage?uploadType=1
    //请求方法:

    private static ObjectMapper mapper = null;


    public static void main(String[] args) throws Exception {
        if (args.length == 0) {
            System.out.println("参数为空");
            return;
        }

        mapper = new ObjectMapper();
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);


        UploadForm uploadForm = readConfig(args);

        HashMap<String, String> params = new HashMap<>();
        params.put("Cookie", uploadForm.getCookie());
        params.put("Referer", uploadForm.getRef());
        params.put("X-Auth-Token", uploadForm.getAuthToken());
        params.put("User-Agent", uploadForm.getUserAgent());

        String[] filePath = uploadForm.getFilePath();
        try {

            for (String s : filePath) {
                System.out.println(s);
                List<DownLoadDetailSql.Model> upload = upload(s, uploadForm, params);
                System.out.println(upload);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void click(List<DownLoadDetailSql.Model> models, HashMap<String, String> params) throws Exception {
        String clickUrl = "http://prod.db-upgrade-tools.ctjsoft.com/api/v1/upgradePackage/";
        for (DownLoadDetailSql.Model model : models) {
            String payLoad = "{\"status\":1}";
            String s = HttpUtil.sendPatch(clickUrl + model.getId(), payLoad, params);
            System.out.println(s);
            Thread.sleep(5000);
        }
    }


    public static List<DownLoadDetailSql.Model> upload(String filePath, UploadForm uploadForm, HashMap<String, String> params) throws Exception {
        List<DownLoadDetailSql.Model> models = upgradePackageBatch(uploadForm, params, filePath);
        return models;
    }

    public static void writeToFile(String fileName, String content) {
        try (FileWriter writer = new FileWriter(fileName)) {
            writer.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String downLoad(DownLoadDetailSql.Model model, HashMap<String, String> params) throws Exception {
        String url = "http://prod.db-upgrade-tools.ctjsoft.com/api/v1/dataTransmission/export/globalFile/" + model.getId();
        return HttpUtil.sendGet(url, params);
    }

    public static List<DownLoadDetailSql.Model> upgradePackageBatch(UploadForm from, HashMap<String, String> params, String filePath) throws Exception {
        ArrayList<DownLoadDetailSql.Model> models = new ArrayList<>();
        File[] files = new File(filePath).listFiles();
        for (File file : files) {
            models.add(upgradePackage(from, params, file));
        }
        return models;
    }

    public static DownLoadDetailSql.Model upgradePackage(UploadForm from, HashMap<String, String> params, File file) throws Exception {
        String url = upgradePackageUrl();
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.addTextBody("appSystemId", from.getSystemId());
        builder.addBinaryBody("file", file, org.apache.http.entity.ContentType.APPLICATION_OCTET_STREAM, URLEncoder.encode(file.getName(), "UTF-8"));
        String res = HttpUtil.sendMultipartPost(url, builder, params);

        System.out.println(res);
        return JsonUtils.toObject(res, DownLoadDetailSql.Model.class);
    }

    public static String upgradePackageUrl() {
//        return "http://localhost:8080/api/user/upload";
        return "http://prod.db-upgrade-tools.ctjsoft.com/api/v1/upgradePackage?uploadType=1";
    }

    public static UploadForm readConfig(String[] args) throws Exception {
        if (args.length == 0) {
            throw new RuntimeException("没有参数");
        }
        if (args.length < 2 || !args[0].equals("--config")) {
            System.err.println("Usage: java -jar MyApp.jar --config /path/to/config.properties");
            System.exit(1);
        }
        String configPath = args[1];
        if (configPath.contains("./")) {
            configPath = System.getProperty("user.dir") + File.separator + configPath.replace("./", "");
        }
        FileReader reader = new FileReader(configPath);
        JsonNode jsonNode = JsonUtils.MAPPER.readTree(reader);
        return JsonUtils.MAPPER.treeToValue(jsonNode, UploadForm.class);

    }


    @Data
    public static class UploadForm extends Base {
        private String listUrl;
        private String downLoadUrl;
        private String json;
        private String systemId;
        private Integer pageSize;
        private String name;
        private String status;
        private Integer page;
        private Integer uploadType;
        private String[] filePath;
    }

    @Data
    public static class Model {
        private String id;
        private String name;
        private Integer status;
    }

    @Data
    public static class Res<T> {
        private Integer totalData;
        private Integer totalPages;
        private T data;
    }
}
